package com.alstudio.utils.android.media.audio.player;

import android.content.Context;
import android.text.TextUtils;

import com.alstudio.utils.android.ALFileManager;
import com.alstudio.utils.android.net.download.ALHttpDownloadListener;
import com.alstudio.utils.android.net.download.ALHttpDownloadManager;
import com.alstudio.utils.android.net.download.ALHttpDownloadTask;
import com.alstudio.utils.android.net.download.ALHttpDownloadTask.ALHttpDownloadErrorCode;
import com.alstudio.utils.log.ALLog;
import com.loovee.imaohu.R;

public class ALAudioPlayTask implements ALHttpDownloadListener {

	private String audioUrl;
	private String fileId;
	private String audioPath;
	private String savePath;
	private String searchPath;
	private String token;

	private ALMusicPlayer mPlayer;
	private Context mContext;
	private ALAudioPlayTaskCallback mCallback;
	private boolean isAudioExsit = false;
	private final String TAG = "ALAudioPlayTask";

	private boolean isCancel;

	private boolean isDownloading = false;
	private ALHttpDownloadTask mDownloadTask;

	private boolean isCountDownRequest = false;

	private boolean isPause = false;

	/**
	 * 设置是否倒计时显示播放进度
	 * 
	 * @param isCountDownRequest
	 */
	public void setCountDownRequest(boolean isCountDownRequest) {
		this.isCountDownRequest = isCountDownRequest;
		if (mPlayer != null) {
			mPlayer.setCountDownRequest(isCountDownRequest);
		}
	}

	public ALAudioPlayTask(Context ctx, String fileid, String savePath) {
		// TODO Auto-generated constructor stub
		mContext = ctx;
		this.fileId = fileid;
		this.savePath = savePath;
		// checkAudioExsitState();
		// mPlayer = new ALMusicPlayer(ctx, audioPath, audioPlayCallback);
	}

	public ALAudioPlayTask(Context ctx, String audioPath) {
		// TODO Auto-generated constructor stub
		mContext = ctx;
		this.audioPath = audioPath;
		mPlayer = new ALMusicPlayer(ctx, audioPath, audioPlayCallback);
	}

	public ALAudioPlayTask(Context ctx, String audioPath,
			ALAudioPlayTaskCallback callback) {
		// TODO Auto-generated constructor stub
		this(ctx, audioPath);
		mCallback = callback;
	}

	public ALAudioPlayTask(Context ctx, String fileid, String savePath,
			ALAudioPlayTaskCallback callback) {
		// TODO Auto-generated constructor stub
		this(ctx, fileid, savePath);
		mCallback = callback;
	}

	public void setFildId(String fildId) {
		if (!TextUtils.isEmpty(this.fileId)) {
			if (!this.fileId.equals(fildId)) {
				mPlayer = null;
			}
		}
		this.fileId = fildId;
	}

	public String getFildId() {
		return fileId;
	}

	public void setSearchPath(String searchPath) {
		this.searchPath = searchPath;
	}

	public String getSearchPath() {
		return searchPath;
	}

	public String getAudioUrl() {
		return audioUrl;
	}

	public void setAudioUrl(String audioUrl) {
		this.audioUrl = audioUrl;
	}

	public String getAudioPath() {
		return audioPath;
	}

	public void setAudioPath(String audioPath) {
		this.audioPath = audioPath;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public void setAudioPlayCallback(ALAudioPlayTaskCallback audioPlayCallback) {
		this.mCallback = audioPlayCallback;
	}

	public synchronized boolean isPlaying() {
		if (mPlayer == null) {
			return false;
		}
		return mPlayer.isPlaying();
	}

	public synchronized boolean isDownloading() {
		return isDownloading;
	}

	public boolean isPause() {
		return isPause;
	}

	public int getDuration() {
		if (mPlayer != null) {
			ALLog.d("时长是多少 " + mPlayer.getMusicDuration());

			return mPlayer.getMusicDuration();
		}
		return 0;
	}

	public int getCurrentPosition() {
		if (mPlayer != null) {
			return mPlayer.getCurrentPosition();
		}
		return 0;
	}

	public void Play() {
		doPlay();
	}

	public void stop() {
		doStop();
	}

	public void resume() {
		doResume();
	}

	public void pause() {
		doPause();
	}

	private void doStop() {
		// TODO Auto-generated method stub
		isCancel = true;
		if (mPlayer != null) {
			mPlayer.stop();
		}
		if (isDownloading) {
			isDownloading = false;
			if (mDownloadTask != null) {
				mDownloadTask.setDownloadStateListener(null);
				mDownloadTask = null;
				ALLog.d("正在下载，停止");
			}
		}
	}

	private void doPlay() {
		checkAudioExsitState();
		if (isAudioExsit) {
			if (mPlayer == null) {
				mPlayer = new ALMusicPlayer(mContext, audioPath,
						audioPlayCallback);
				mPlayer.setCountDownRequest(isCountDownRequest);
			}
			mPlayer.play();
			isDownloading = false;
		} else {
			if (TextUtils.isEmpty(audioUrl)) {
				getDefaultDownloadUrl();
			}
			mDownloadTask = ALHttpDownloadManager.startDownload(mContext,
					audioUrl, savePath, token, fileId, this);
			ALLog.d("开始下载音频文件");
		}
	}

	private void doPause() {
		isCancel = true;
		if (mPlayer != null) {
			mPlayer.pause();
		}
		if (isDownloading) {
			isDownloading = false;
			if (mDownloadTask != null) {
				mDownloadTask.setDownloadStateListener(null);
				mDownloadTask = null;
				ALLog.d("正在下载，停止");
			}
		}
	}

	private void doResume() {
		if (mPlayer != null) {
			mPlayer.resume();
		}
	}

	/**
	 * 获取下载连接
	 */
	private void getDefaultDownloadUrl() {
		String mediaServerIp = null;
		String mediaServerPort = null;

		// if (App.serverInfo == null) {
		// mediaServerIp = "img1.imeach.com";
		// mediaServerPort = "8080";
		// } else {
		// mediaServerIp = App.serverInfo.getMediaServerIp();
		// mediaServerPort = App.serverInfo.getMediaServerPort();
		// }
		// audioUrl = "http://" + mediaServerIp + ":" + mediaServerPort
		// + "/MediaServerMblove/servlet/Proxy/AudioServlet/" + fileId;
		//
		// token = App.myAccount.getToken();
	}

	private void checkAudioExsitState() {
		if (!TextUtils.isEmpty(fileId)) {
			if (!TextUtils.isEmpty(savePath)) {
				if (!ALFileManager.isFileExsit(savePath)) {
					ALFileManager.createFile(savePath);
					ALLog.d("音频文件保存文件夹不存在,已创建");
				} else {
					if (!savePath.endsWith("/")) {
						savePath += "/";
					}

					String path = savePath + fileId;

					if (ALFileManager.isFileExsit(path)) {
						isAudioExsit = true;
						ALLog.d("音频文件已经存在,不需要下载");
					}
				}
				audioPath = savePath + fileId;
			}
		} else if (!TextUtils.isEmpty(audioPath)) {
			isAudioExsit = true;
		}
	}

	private ALMusicPlayerCallback audioPlayCallback = new ALMusicPlayerCallback() {

		@Override
		public void onMusicStop() {
			// TODO Auto-generated method stub
			isPause = false;
			if (mCallback != null) {
				mCallback.onMusicStop();
			}
		}

		@Override
		public void onMusicProgressChanged(int second) {
			// TODO Auto-generated method stub
			if (mCallback != null) {
				mCallback.onMusicProgressChanged(second);
			}
		}

		@Override
		public void onMusicPlay() {
			// TODO Auto-generated method stub
			isPause = false;
			if (mCallback != null) {
				mCallback.onMusicPlay();
			}
		}

		@Override
		public void onMusicPause() {
			// TODO Auto-generated method stub
			isPause = true;
			if (mCallback != null) {
				mCallback.onMusicPause();
			}
		}

		@Override
		public void onMusicError() {
			// TODO Auto-generated method stub
			isPause = false;
			if (mCallback != null) {
				mCallback.onMusicError();
			}
		}
	};

	public interface ALAudioPlayTaskCallback extends ALMusicPlayerCallback {
		public void onUpdateProcess(int percent); // 更新进度

		public void onDownloadFinish(String path); // 完成下载

		public void onPreDownload(); // 准备下载

		public void onDownloadFail(ALHttpDownloadErrorCode code); // 下载错误
	}

	@Override
	public void onUpdateProcess(final ALHttpDownloadTask info) {
		// TODO Auto-generated method stub
		ALLog.d(mContext.getString(R.string.TxtDownloadingProcess) + " "
				+ info.getDownloadPercent());
		if (mCallback != null) {
			mCallback.onUpdateProcess(info.getDownloadPercent());
		}
	}

	@Override
	public void onDownloadFinish(ALHttpDownloadTask info) {
		// TODO Auto-generated method stub
		ALLog.d("下载完成！");
		isAudioExsit = true;
		isDownloading = false;
		mDownloadTask = null;
		if (!isCancel) {
			if (mCallback != null) {
				mCallback.onDownloadFinish(info.getFilePath());
			}
			if (!TextUtils.isEmpty(info.getUrl())
					&& info.getUrl().equals(audioUrl)) {
				doPlay();

			} else {
				ALLog.d("下载的file id " + info.getUrl() + " 与当前的不一致  " + audioUrl);
			}
		} else {
			ALLog.d("用户已经取消播放");
		}
	}

	@Override
	public void onPreDownload(final String name) {
		// TODO Auto-generated method stub
		ALLog.d("准备开始下载");
		isDownloading = true;
		if (mCallback != null) {
			mCallback.onPreDownload();
		}
	}

	@Override
	public void onDownloadFail(ALHttpDownloadErrorCode code, final String name,
			ALHttpDownloadTask info) {
		// TODO Auto-generated method stub
		ALLog.d("下载失败:" + code);
		isDownloading = false;
		mDownloadTask = null;
		if (mCallback != null) {
			mCallback.onDownloadFail(code);
		}

	}

	// /********************************************** 声道切换
	// *****************************************************/
	//
	// private static AudioManager audioManager = (AudioManager) App.ctx
	// .getSystemService(Context.AUDIO_SERVICE);
	//
	// private static SensorManager sm = (SensorManager) App.ctx
	// .getSystemService(Context.SENSOR_SERVICE);
	//
	// private void initAudioSensorChangeListener() {
	//
	// sm.registerListener(new SensorEventListener() {
	// @Override
	// public void onSensorChanged(SensorEvent event) {
	// float[] its = event.values;
	// if (its != null
	// && event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
	// if (its[0] <= 3.0) {// 贴近手机
	// audioManager.setMode(AudioManager.MODE_IN_CALL);// 把模式调成听筒放音模式
	// ALLog.d( "听筒模式");
	// } else {// 远离手机
	// audioManager.setMode(AudioManager.MODE_NORMAL);// 把模式调成喇叭放音模式
	// ALLog.d( "外放模式");
	// }
	// }
	// }
	//
	// @Override
	// public void onAccuracyChanged(Sensor sensor, int accuracy) {
	// }
	// }, sm.getDefaultSensor(Sensor.TYPE_PROXIMITY),
	// SensorManager.SENSOR_DELAY_UI);
	// }

}
